﻿module Sustainalytics.Tools.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;

    export class ToolsService implements IToolsService {

        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: Common.INotificationFactory;
        private staticObjectsAdmin: CommonAdmin.IStaticObjects;
        private $upload: any;

        constructor(
            $q: ng.IQService,
            $http: ng.IHttpService,
            notificationFactory: Common.INotificationFactory,
            staticObjectsAdmin: CommonAdmin.IStaticObjects,
            $upload) {

            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
            this.staticObjectsAdmin = staticObjectsAdmin;
            this.$upload = $upload;
        }

        public importEsgRatings(dataFile: ArrayBuffer, contentType: string) {            
            return this.$upload.http({
                url: "/esgratingserv/api/v1/esgratings", 
                headers: { "Content-Type": contentType }, 
                data: dataFile
            });
        }

        public importClaims(dataFile: File, processAll: boolean) {
            return this.$upload.upload({
                url: "/claimsserv/api/v1/claims",
                method: "POST",
                data: { formData: { ProcessAllContent: processAll} },
                file: dataFile
            });
        }

        public importEsgFocusThresholds(dataFile: File, isPercentile: boolean): ng.IPromise<{}> {
            return this.$upload.upload({
                url: "/esgratingserv/api/v1/esgfocusthreshold",
                method:"POST",
                file: dataFile,
                data: { isPercentile:isPercentile  }
            });
        }

        public lastSyncDate(): ng.IPromise<Date> {
            var ctx = this;

            var def = ctx.$q.defer();
            var promise = ctx.$http.get("/claimsserv/api/v1/claims/lastSyncDate");

            promise
                .success(function (data) {
                def.resolve(data);
            })
                .error(function (data, status, headers, config) {
                def.reject({ data: data, status: status, headers: headers, config: config });
            });

            return def.promise;
        }
    }

    // register service with Tools Angular module
    var mod = angular.module(toolsAdminModuleName);
    
    mod.service('ToolsService',
        ['$q', '$http', 'notificationFactory', 'staticObjectsAdmin', '$upload', ToolsService]);
}